-- SERVER SIDE

-- Creates the Database
GetEnMap = string.Replace(game.GetMap(),"_","")
GetEnMap = string.Replace(GetEnMap,".","")
GetEnMap = "apple_tmd_entities5_"..GetEnMap
if sql.TableExists(GetEnMap) then
MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesDB",Color(255,255,255),"] Database '"..GetEnMap.."' Already Exists!\n")
	else
	if (!sql.TableExists(GetEnMap)) then
		local Query = "CREATE TABLE "..GetEnMap.." ( ID int, Name varchar(255), XPos varchar(255), YPos varchar(255), ZPos varchar(255), Pitch varchar(255), Yaw varchar(255), Roll varchar(255))"
		local Result = sql.Query(Query)
		if (sql.TableExists(GetEnMap)) then
			--MsgN("[TDM-CustomEntities] Successfully Created Database '"..GetEnMap.."'!")
			MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesDB",Color(255,255,255),"] Successfully Created Database '"..GetEnMap.."'!\n")
		else
			--MsgN("[TDM-CustomEntities] Database '"..GetEnMap.."' Was Not Created!")
			MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesDB",Color(255,255,255),"] Database '"..GetEnMap.."' Was Not Created!\n")
			MsgN( sql.LastError( Result ) )
		end	
	end
end


function TDMCreateEntity(len, ply)
if !ply:IsSuperAdmin() then return end
local EntName = net.ReadString( )

local LastEntityIDCreated = tonumber(sql.QueryValue( "SELECT ID FROM "..GetEnMap.." ORDER BY ID DESC LIMIT 1" ))
if LastEntityIDCreated == nil then
	LastEntityIDCreated = 0
end

	local vAngle = ply:GetAimVector()
	local UpAngle = tostring(vAngle:Angle())
	local data = string.Explode(" ", UpAngle)

local LastEntityIDCreated = (LastEntityIDCreated + 1)
	--MsgN("[TDM-CustomEntities] Entity Was Created Successfully, EntityID:: "..LastEntityIDCreated)
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesAdd",Color(255,255,255),"] Entity Was Created Successfully, EntityID: ",Color(0,255,0),""..LastEntityIDCreated.."\n")
	local AddCE = sql.Query( "INSERT INTO "..GetEnMap.." (`ID`, `Name`, `XPos`, `YPos`, `ZPos`, `Pitch`, `Yaw`, `Roll`) VALUES ('"..tonumber(LastEntityIDCreated).."', '"..EntName.."', '"..math.Round(tonumber(ply:GetPos().x)).."', '"..math.Round(tonumber(ply:GetPos().y)).."', '"..math.Round(tonumber(ply:GetPos().z)).."', '"..math.Round(tonumber(data[1])).."', '"..math.Round(tonumber(data[2])).."', '"..math.Round(tonumber(data[3])).."' ) ")
	if !AddCE then 
		--MsgN("[TDM-CustomEntities] Entity Was Created")
		MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesAdd",Color(255,255,255),"] Entity Was Created\n")
		umsg.Start("apple_tdm_entycre",ply)
			umsg.String(LastEntityIDCreated)
			umsg.String(EntName)
			umsg.String(math.Round(tonumber(ply:GetPos().x)))
			umsg.String(math.Round(tonumber(ply:GetPos().y)))
			umsg.String(math.Round(tonumber(ply:GetPos().z)))
		umsg.End()
		AutoFixEntityID()
	return end
end
net.Receive("apple_tdm_customentities2", TDMCreateEntity)


function TDMGotoPosE(len, ply)
if !ply:IsSuperAdmin() then return end
local XPos = net.ReadString( )
local YPos = net.ReadString( )
local ZPos = net.ReadString( )
ply:SetPos(Vector(XPos,YPos,ZPos))
umsg.Start("apple_tdm_wentpose", ply)
	umsg.Short(XPos)
	umsg.Short(YPos)
	umsg.Short(ZPos)
umsg.End()
end
net.Receive("apple_tdm_customentitiesr9", TDMGotoPosE)


-- Deletes Entities on the Database
function TDMDeleteEntity(len, ply)
if !ply:IsSuperAdmin() then return end
args = net.ReadString( )
if tonumber(args) == nil then return end

local GetEntityName = sql.QueryValue( "SELECT Name FROM "..GetEnMap.." WHERE ID = "..args.."" ) -- Will check to see if team even exists
if GetEntityName == nil then 
	--MsgN("[TDM-CustomEntities] Entity Does Not Exist!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesDelete",Color(255,255,255),"] Entity Does Not Exist!\n")
return end

local GetDeleteInfoE = sql.Query( "DELETE FROM "..GetEnMap.." WHERE ID = "..args.."" ) -- Attempted to delete the team
if !GetDeleteInfoE then -- If team is deleted correctly, then it will run this fuctions
team.SetScore(args, 0)
	local oldents = ents.FindByClass(GetEntityName)
	for _,v in pairs(oldents) do v:Remove() end
	umsg.Start("apple_tdm_deletentity",ply)
	umsg.String(GetEntityName)
	umsg.End()
	--MsgN("[TDM-CustomEntities] "..GetEntityName.." Has Been Successfully Deleted!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-CustomEntitiesDelete",Color(255,255,255),"] ",Color(0,255,0),""..GetEntityName.." Has Been Successfully Deleted!\n")
	AutoFixEntityID()
return end
end
net.Receive("apple_tdm_customentities5", TDMDeleteEntity)



if sql.TableExists(GetEnMap) then
	function AutoFixEntityID()
		local AutoFixEntityID = sql.Query( "SELECT * FROM "..GetEnMap.."" )
		if !AutoFixEntityID then 
			CustomEntites = {}
			net.Start( "apple_tdm_customentitiesr5" )
				net.WriteTable(CustomEntites)
			net.Broadcast()
			umsg.Start("apple_tdm_updateliste")
			umsg.End()
		return end
			CustomEntites = {}
			for k, v in pairs( AutoFixEntityID ) do
				local oldents = ents.FindByClass(v['Name'])
				for _,v in pairs(oldents) do v:Remove() end
				
				sql.Query( "UPDATE "..GetEnMap.." SET ID = "..k.." WHERE ID = "..v['ID'].."" )
				--MsgN("[TDM-AutoEntitiesIndex] Entity: "..v['Name'].."("..k..") have been repaired!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-AutoFixEntitiesIndex",Color(255,255,255),"] Entity: ",Color(0,255,0),""..v['Name'].."",Color(255,255,255),"(",Color(0,0,255),""..k.."",Color(255,255,255),") have been repaired!\n")
				CustomEntites[k] = {
					ID = tostring(v['ID']),
					Name2 = tostring(v['Name']),
					XPos = tostring(v['XPos']),
					YPos = tostring(v['YPos']),
					ZPos = tostring(v['ZPos'])
				}
				timer.Simple(1,function()
					local ent = ents.Create(v['Name'])
					ent:SetPos(Vector(tonumber(v['XPos']),tonumber(v['YPos']),tonumber(v['ZPos'])))
				--	ent:SetAngles(Angle(tonumber(v['Pitch']),tonumber(v['Yaw']),tonumber(v['Roll'])))
				--	ent:SetModel("models/props_junk/wood_crate001a_damaged.mdl")
				--	ent:SetColor(team.GetColor(tonumber(v['TID'])))
				--	ent:SetMoveType(0)
					ent:Spawn()
				--	ent:EmitSound("apptdm/njoin2.mp3", 500, 200)
				end)
			end
		net.Start( "apple_tdm_customentitiesr5" )
			net.WriteTable(CustomEntites)
		net.Broadcast()
			umsg.Start("apple_tdm_updateliste")
			umsg.End()
	end
AutoFixEntityID()
end


function TDMReloadEntites(len, ply)
AutoFixEntityID()

	for k,v in pairs(player.GetAll()) do
		if v == ply then
			umsg.Start("apple_tdm_reloadentites",ply)
			umsg.End()
		else
			umsg.Start("apple_tdm_reloadentitesa",v)
				umsg.Short(ply:Team())
				umsg.String(ply:Nick())
			umsg.End()
		end
	end
end
net.Receive("apple_tdm_customentitiesr42", TDMReloadEntites)


function CallEnties()
	net.Start( "apple_tdm_customentitiesr5" )
		net.WriteTable(CustomEntites)
	net.Broadcast()
			umsg.Start("apple_tdm_updateliste")
			umsg.End()
end